package com.starblink.android.guang

//import com.tencent.bugly.crashreport.CrashReport
import android.content.Context
import android.content.Intent
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ProcessUtils
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.shuyu.gsyvideoplayer.cache.CacheFactory
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.BaseApplication
import com.starblink.android.basic.config.GuangConfig
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.room.mana.SkTraceDatabaseManager
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.charles.CharlesManager
import com.starblink.android.common.player.ExoMediaPlayerFactory
import com.starblink.android.guang.report.GuangFBCrashReporter
import com.starblink.basic.autosize.AutoSizeConfig
import com.starblink.basic.log.report.ErrorReporter
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.CommUtils
import com.starblink.imgsearch.camera.ICameraApp
import com.starblink.library.data.transfer.FlutterSpTransfer
import com.starblink.login.ILoginApp
import com.starblink.video.player.VideoView
import com.starblink.video.player.VideoViewConfig
import com.starblink.video.player.VideoViewManager
import com.starblink.web.broadcast.WebViewInitBoastCast
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager
import java.util.concurrent.Executors


class GuangApp : BaseApplication(), ICameraApp, ILoginApp {

    override fun onCreate() {
        FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG)
        super.onCreate()
    }

    override fun onInit() {
        super.onInit()
        initNetWorkReceiver(BuildConfig.FLAVOR)
        ErrorReporter.register(GuangFBCrashReporter())

        //SPM
//        SensorsDataAPI.init(this)
        //埋点tracker初始化
        SkTraceDatabaseManager.saveApplication(this)
        GTrackerAssistUtils.setup()

        AppsflyerManager.initAppsflyer(this)
        initAdjust()

        GuangAppStateManager.init(this)

        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
        //EXOPlayer内核，支持格式更多

        CacheFactory.setCacheManager(ExoPlayerCacheManager::class.java)//exo缓存模式，支持m3u8，只支持exo

        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);

//        if (!BaseApiClient.isPub()) {
//            CrashReport.initCrashReport(this, "e80ef4e9d0", false);
//        }

//        ExoSourceManager.setExoMediaSourceInterceptListener(object :
//            ExoMediaSourceInterceptListener {
//            override fun getMediaSource(
//                dataSource: String,
//                preview: Boolean,
//                cacheEnable: Boolean,
//                isLooping: Boolean,
//                cacheDir: File
//            ): MediaSource? {
//                //如果返回 null，就使用默认的
//                return null
//            }
//
//            /**
//             * 通过自定义的 HttpDataSource ，可以设置自签证书或者忽略证书
//             * demo 里的 GSYExoHttpDataSourceFactory 使用的是忽略证书
//             */
//            override fun getHttpDataSourceFactory(
//                userAgent: String,
//                listener: TransferListener?,
//                connectTimeoutMillis: Int,
//                readTimeoutMillis: Int,
//                mapHeadData: Map<String, String>,
//                allowCrossProtocolRedirects: Boolean
//            ): DataSource.Factory {
//                //如果返回 null，就使用默认的
//                val factory = GSYExoHttpDataSourceFactory(
//                    userAgent, listener,
//                    connectTimeoutMillis,
//                    readTimeoutMillis, allowCrossProtocolRedirects
//                )
//                factory.setDefaultRequestProperties(mapHeadData)
//                return factory
//            }
//        })

        //播放器配置，注意：此为全局配置，按需开启
        VideoViewManager.setConfig(
            VideoViewConfig.newBuilder()
                .setLogEnabled(BuildConfig.DEBUG) //调试的时候请打开日志，方便排错
                /** 软解，支持格式较多，可通过自编译so扩展格式，结合 [xyz.doikki.dkplayer.widget.videoview.IjkVideoView] 使用更佳  */ //                .setPlayerFactory(IjkPlayerFactory.create())
                //                .setPlayerFactory(AndroidMediaPlayerFactory.create()) //不推荐使用，兼容性较差
                /** 硬解，支持格式看手机，请使用CpuInfoActivity检查手机支持的格式，结合 [xyz.doikki.dkplayer.widget.videoview.ExoVideoView] 使用更佳  */
                .setPlayerFactory(ExoMediaPlayerFactory.create()) // 设置自己的渲染view，内部默认TextureView实现
                //                .setRenderViewFactory(SurfaceRenderViewFactory.create())
                // 根据手机重力感应自动切换横竖屏，默认false
                //                .setEnableOrientation(true)
                // 监听系统中其他播放器是否获取音频焦点，实现不与其他播放器同时播放的效果，默认true
                //                .setEnableAudioFocus(false)
//                 视频画面缩放模式，默认按视频宽高比居中显示在VideoView中
                .setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT)
                // 适配刘海屏，默认true
                //                .setAdaptCutout(false)
                // 移动网络下提示用户会产生流量费用，默认不提示，
                // 如果要提示则设置成false并在控制器中监听STATE_START_ABORT状态，实现相关界面，具体可以参考PrepareView的实现
                //                .setPlayOnMobileNetwork(false)
                // 进度管理器，继承ProgressManager，实现自己的管理逻辑
                //                .setProgressManager(new ProgressManagerImpl())
                .build()
        )

        initCharles()
        when (ProcessUtils.getCurrentProcessName()) {
            this.packageName -> {
                // 主进程初始化...
                initWebViewPool()
            }
        }
    }

    private fun initWebViewPool() {
        //不启用web进程
//        WebUtil.initWebViewPool(this)

        // 用广播提前拉起 :web进程
        sendBroadcast(Intent(this, WebViewInitBoastCast::class.java))
    }

    //初始化抓包
    private fun initCharles() {
        //开启抓包
        CharlesManager.initHeaderParams(
            deviceId = UserDataCenter.getDeviceId(CommUtils.getContext()),
            getCurrSvrCfgEnvName = {
                BaseApiClient.getCurrSvrCfgEnvName() ?: ""
            },
            getLocalCountry = {
                UserDataCenter.getLocalCountry()
            },
            isPub = {
                BaseApiClient.isPub()
            },
            buildTime = BuildConfig.BUILD_TIME
        )
    }

    ///接入 Adjust SDK
    private fun initAdjust() {
        val appToken = "osmb1gy5va4g"
        //在向 App Store 提交应用程序前，将环境设置变为 AdjustConfig.ENVIRONMENT_PRODUCTION
        val environment: String = AdjustConfig.ENVIRONMENT_PRODUCTION
        val config = AdjustConfig(this, appToken, environment)
        config.setLogLevel(LogLevel.WARN)
        Adjust.onCreate(config)
        registerAdjustCallBack()
    }


}